<!-- 上传图片 -->

<template>
  <div
    class="border-dotted border-2 aspect-square rounded w-32 cursor-pointer relative"
    @click="!modelValue && uploadRef.click()"
  >
    <input ref="uploadRef" type="file" accept=".png, .jpg, .jpeg" @change="handleChange" class="hidden" />
    <a-image
      :preview-visible="inPreview"
      @preview-visible-change="
        () => {
          inPreview = false
        }
      "
      :src="modelValue"
      class="h-full w-full flex bg-gray-100 rounded"
      fit="cover"
    >
      <template #error>
        <div class="h-full tracking-widest flex items-center justify-center text-sm">
          <template v-if="modelValue">
            <span class="text-red-500">加载</span>
            <Icon class="text-red-500" icon="mdi:close-outline" />
            <span class="text-red-500">失败</span>
          </template>
          <template v-else>
            <span class="text-gray-400 text-center">点击上传</span>
          </template>
        </div>
      </template>
    </a-image>
    <div
      :class="{
        'hover:opacity-100 w-full h-full top-0 left-0 z-10 transition-all': modelValue,
      }"
      class="absolute bg-gray-400 bg-opacity-60 flex opacity-0 items-end justify-end p-2 gap-x-1"
    >
      <Icon
        @click.stop="inPreview = true"
        icon="icon-park-twotone:preview-open"
        class="transition-all h-1/5 w-1/5 p-0.5 text-white mine-icon hover:bg-[#333]"
      />
      <Icon
        @click.stop="clearFile"
        icon="ic:twotone-delete"
        class="transition-all h-1/5 w-1/5 p-0.5 text-white mine-icon hover:bg-[#333]"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
const uploadRef = ref()
const props = withDefaults(
  defineProps<{
    modelValue: string
    api?: (e: FormData) => Promise<{ url: string }>
    // resFormat?: (e: any) => string
    maxSize?: number
    waterMark?: false | string // 目前只支持base64 即:无Api
    onlyBtn?: boolean
  }>(),
  {
    // resFormat: (e: any) => e.url,
    maxSize: 5,
  },
)

const inPreview = ref(false)
const emits = defineEmits(['update:modelValue'])

const handleChange = async ({ target }: any) => {
  const { maxSize, api, waterMark } = props
  let file = target.files[0]
  const { size, type } = file
  if (size > maxSize * 1024 * 1024) return Message.warning(`支持上传的最大文件为${maxSize}M`)
  if (!['image/png', 'image/jpeg'].includes(type)) return Message.warning(`仅支持上传jpg格式或者png格式`)
  let image: string = ''
  if (!api || waterMark) {
    image = (await FileToBase64(file)) as string
    if (waterMark) {
      image = await addWatermark({
        target: image,
        text: waterMark,
      })
    }
  }
  if (api) {
    if (waterMark) {
      file = base64ToFile(image, file.name)
    }
    const formData = new FormData()
    formData.append('file', file)
    const { url } = await api(formData)
    image = url
  }
  emits('update:modelValue', image)
  Message.success('选择成功')
}

const clearFile = async () => {
  // await useConfirm()
  emits('update:modelValue', '')
  uploadRef.value.value = ''
}
</script>
